#pragma once
#include <iostream>
#include <cstring>
#include <sys/epoll.h>
#include "log.hpp"
#include "Err.hpp"

const static int gsize = 32;

class Epoller
{
public:
    Epoller()
    {}
    // 创建Epoller模型
    void Create()
    {
        epfd = epoll_create(gsize);
        if(epfd < 0)
        {
            LogMessage(Fatal, "epoll create fail, error: %d, errStr: %s", errno, strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
    }
    // 控制添加描述符的动作，读 | 写
    void CtlEvent(int fd, uint32_t event, int op)
    {
        struct epoll_event events;
        events.data.fd = fd;
        events.events = event;
        int n = epoll_ctl(epfd, op, fd, &events);
        if(n < 0)
            LogMessage(Warring, "epoll add fail, fd: %d, error: %d, errStr: %s", fd, errno, strerror(errno));
    }
    // 拉取以就绪对象
    int Wait(struct epoll_event *events, int maxevents, int timeout)
    {
        return epoll_wait(epfd, events, maxevents, timeout);
    }
    // 删除控制元素
    bool DelEvent(int fd)
    {
        return epoll_ctl(epfd, EPOLL_CTL_DEL, fd, nullptr) == 0;
    }

    ~Epoller()
    {
        close(epfd);
    }
private:
    int epfd;
};